package com.mg.smarttask.server;

import java.util.Date;
import java.util.ArrayList;
import java.util.List;
//import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.mg.smarttask.client.Note;
import com.mg.smarttask.client.NoteService;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class NoteServiceImpl extends RemoteServiceServlet implements NoteService {
	private static final long serialVersionUID = 1L;
	
//	private static final Logger LOG = Logger.getLogger(NoteServiceImpl.class.getName());
	private static final PersistenceManagerFactory PMF = JDOHelper
	.getPersistenceManagerFactory("transactions-optional");
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List getNotesList(long UserId) {
		PersistenceManager pm = getPersistenceManager();
		Query query = pm.newQuery(NoteDO.class,"ownerId=="+UserId+"");
		query.setOrdering("modificationDate descending");
		List result = new ArrayList();
		try {
			List<NoteDO> results = (List) query.execute();
			for(NoteDO note : results){
				result.add(convertNoteDo2Note(note));
			}
		} finally{
			pm.close();
		}
		return result;
	}

	@Override
	public boolean createNote(Note note) {
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.makePersistent(new NoteDO(note.getTitle(), new Text(note.getDescription()), note.getIsShared(),
					note.getIsDone(),note.getCreationDate(), note.getModificationDate()));
		} finally{
			pm.close();
		}
		return true;
	}

	@Override
	public void deleteNote(Note note) {
		PersistenceManager pm = getPersistenceManager();
		NoteDO object = pm.getObjectById(NoteDO.class,note.getNoteId());
		try {
			pm.deletePersistent(object);
		} finally{
			pm.close();
		}
		
	}
	private PersistenceManager getPersistenceManager() {
		return PMF.getPersistenceManager();
	}
	
	private Note convertNoteDo2Note(NoteDO note){		
		Note rNote = new Note(note.getTitle(), note.getDescription(), note.getIsShared(),
				note.getIsDone(),note.getCreationDate(), note.getModificationDate(),note.getOwnerId());
		rNote.setNoteId(note.getId());
		return rNote;
	}

	@Override
	public boolean editNote(Note note) {
		PersistenceManager pm = getPersistenceManager();
		NoteDO object = pm.getObjectById(NoteDO.class,note.getNoteId());
		object.setTitle(note.getTitle());
		object.setIsShared(note.getIsShared());
		object.setDescription(new Text(note.getDescription()));
		object.setIsDone(note.getIsDone());
		object.setModificationDate(new Date());
		try {
			pm.makePersistent(object);
		} finally{
			pm.close();
		}
		return true;
	}

}
